package com.sand.util;



import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint("/ws/websocket/{rid}/{isUser}")
public class LoginSocket {
    private static Map<Integer, Session> map =new HashMap<>();

    //用户登录
    @OnOpen
    public void OnOpen(Session session, @PathParam("rid") int rid,@PathParam("isUser") int isUser){
        //获取登录ip地址
        RemoteEndpoint.Async async = session.getAsyncRemote();
        InetSocketAddress addr = (InetSocketAddress) getFieldInstance(async,"base#socketWrapper#socket#sc#remoteAddress");
        //根据ip地址获取登录地址
        String city = CityQuery.getCity(addr.toString());

        switch (isUser){
            case 1:
                HashMap<String, Object> rest = new HashMap<>();
                System.out.println("后台连接用户："+session.getRequestURI());

                rest.put("city",city);
                //判断当前账号是否已登录,如果已登录，退出前一个账号
                if(map.containsKey(rid)){
                    //获取重复登录的账号
                    Session oldSession = map.get(rid);
                    map.remove(rid);
                    System.out.println("当前账号已在其他地方登录!");
                    rest.put("code",1);
                    rest.put("txt","当前账号已在其他地方登录!<br/>登录地址为《"+city+"》");
                    oldSession.getAsyncRemote().sendText(JSON.toJSONString(rest));
                    rest.put("code",0);
                    session.getAsyncRemote().sendText(JSON.toJSONString(rest));
                    //退出账号
                    OnClose(oldSession,rid);
                }else {
                    rest.put("code",0);
                    session.getAsyncRemote().sendText(JSON.toJSONString(rest));
                }
                map.put(rid,session);
                System.out.println("后台用户当前连接数："+map.size());
                break;
            case 2:
                HashMap<String, Object> rest2 = new HashMap<>();
                System.out.println("前台访问用户："+session.getRequestURI());

                rest2.put("city",city);
                rest2.put("code",0);
                session.getAsyncRemote().sendText(JSON.toJSONString(rest2));
                break;
        }
    }

    //用户发送消息
    @OnMessage
    public void OnMessage(String msg,Session session){
        System.out.println("发送的消息内容："+msg);
    }
    //用户退出
    @OnClose
    public void OnClose(Session session,@PathParam("rid") int rid){
        if(map.containsKey(rid)) {
            map.remove(rid);
        }
        System.out.println("退出用户："+session.getRequestURI());
    }
    //异常信息
    @OnError
    public void OnError(Throwable e){
        System.out.println("异常信息："+e.getMessage());
    }

    private static Object getFieldInstance(Object obj, String fieldPath) {
        String fields[] = fieldPath.split("#");

        for (String field : fields) {
            obj = getField(obj, obj.getClass(), field);

            if (obj == null) {
                return null;

            }

        }

        return obj;

    }

    private static Object getField(Object obj, Class clazz, String fieldName) {
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                Field field;

                field = clazz.getDeclaredField(fieldName);

                field.setAccessible(true);

                return field.get(obj);

            } catch (Exception e) {
            }

        }

        return null;

    }

}
